<?php

namespace Home\Controller;

use Utuo\ForegroundController;

class ArticleController extends ForegroundController {
	
	public function _initialize() {
		layout(false);
		$this->setModelName('Site');
	}
	
	private function getCategory( $id ) {
		$id or $this->catId = $id = I('id', 0, 'intval');
		$map['cid'] = $this->sid;
		$map['status'] = 1;
		$map['is_deleted'] = 0;
		$category = M('ArticleCategory')->where($map)->find($id);
		$temparr=$this->getTopCategory($category['id']);
		$category['topCategory']=$temparr['id'];
	    $this->assign('category', $category);
		$this->assign('cat_id', $id);
		return $category;
	}
	//获取顶级目录
	private function getTopCategory($id){
		 
		$data=M('ArticleCategory')->where("id=%d",$id)->field("id,pid")->find();
		 
		if($data['pid']!=0)
		{
			$data=$this->getTopCategory($data['pid']);
		}
		 
		return $data;
	}
	// 文章列表
	public function listAction() {
		$category = $this->getCategory();
	
		$this->doDisplay($category, 'list', $this->modelName."/Article/");
	}
	
	// 文章详情页
	public function showAction() {
		$id = I('id', 0, 'intval');
		$map['art.cid'] = $this->sid;
		$map['art.status'] = 1;
		$map['art.is_deleted'] = 0;
		$map['art.id'] = $id;
		$article = M('Article art')->where($map)->join("__ARTICLE_CONFIG__ cfg on cfg.id=art.id", 'LEFT')->find();
		M('Article')->where("id=%d", $id)->setInc("hits", 1);
		$this->assign('article', $article);
		$category = $this->getCategory($article['cat_id']);
		$this->doDisplay($category, 'show', $this->modelName."/Article/");
	}
	
	// 更多文章
	public function moreAction() {
		$this->getCategory();
		$catId = I("cat",0,"intval");
		$list = $this->lists($catId, true, $this->getPageSize(), $this->getPage());
	    $totalPages = ceil($list['count'] / $this->getPageSize()); //总页数
		// 显示更多文章数据
		$data = array();
		if($this->getPage() <= $totalPages) {
			$data = $list['data'];
			foreach ($data as &$v) $v['url'] = get_url($this->sid, 'Article', 'show', "id={$v['id']}");
		}
	
		$this->ajaxSuccess(M()->getLastSql(), $data);
	}
	
	// 获得列表 
	private function lists($cateId = 0, $paginate = false, $pageSize = 10, $p = 1) {
		$condition = array(
				"cid" => $this->sid,
				"is_deleted" => 0,
				"status" => 1,
				"cat_id" => $cateId, );
		$m = M("Article")->where($condition);
		$new_m = clone $m;
		// 分页处理
		if($paginate) {
			$m->limit($this->getPageSize())->page($this->getPage());
			$contentCount = $new_m->count();
		}
		$contentLists = $m->order('update_time desc')->select();
		return array('count' => $contentCount, 'data' => $contentLists);
	}
	
	// 按设置的模板显示
	private function doDisplay( $category, $tplType, $rootPath ) {
		$siteThemeTpl = D("SiteThemeTpl", "Logic");
		$tpl = $siteThemeTpl->getCategoryTpl( unserialize($category['tpl_config']), $tplType );
		
		$this->display($tpl ? $rootPath.$tpl : $rootPath.ACTION_NAME);
	}
		
}